package com.xinxin.leetcode.problem637;

import com.xinxin.leetcode.common.CommonUtil;
import com.xinxin.leetcode.common.TreeNode;
import com.xinxin.leetcode.common.TreeUtil;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author ShiXinXin
 * @date 2020-02-12 23:37
 */
class Solution {
    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> list = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            double sum = 0;
            int len = queue.size();
            for (int i = 0; i < len; i++) {
                TreeNode node = queue.poll();
                sum += node.val;
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
            list.add(sum / len);
        }
        return list;
    }

    public static void main(String[] args) {
        TreeNode root = TreeUtil.createTree(CommonUtil.createArr(3, 9, 0, 0, 20, 15, 0, 0, 7, 0, 0));
        System.out.println(new Solution().averageOfLevels(root));
    }
}
